var last_x;
var last_y;
var ox;
var oy;

var polygon_arr = "";
var polygon_arr_temp = "";
var hit_it=false;
var mouseclick = function(_event) {
	//console.log("mouseclick");
	var event = _event.changedTouches && _event.changedTouches[0] || _event
	last_x = event.clientX;
	last_y = event.clientY;
	if (isDrawing) {// 判断是否绘制模式，true绘制模式 false选择模式
		// console.log("绘制模式");
		is_mouse_down = true;

		switch (selected_tool_id) {

		case "rect":
			var rect_select = draw.rect(100, 100);

			rect_select.attr({
				fill : '#ffffff',
				"stroke" : '#000',
				"stroke-width" : 1
			});
			rect_select.stroke({
				color : '#000',
				opacity : 1,
				width : 1
			});
			
			rect_select.move(event.clientX, event.clientY - canvas_offset_top);
			selected_tool = rect_select;
			selected_tool.data({"bordercolor":"#000","fill":"#fff","radius-x":5,"radius-y":5});
			break;
		case "image":
			//
			var image = draw.image('logo.png', 48, 48).transform({
				scaleX : 1,
				scaleY : 1
			});
			image.move(event.clientX, event.clientY - canvas_offset_top);
			selected_tool = image;

			break;
		case "circle":
			// var circle=draw.circle(1);
			var circle = draw.ellipse(100, 100);
			circle.center(event.clientX, event.clientY - canvas_offset_top)
			circle.attr({
				fill : '#ffffff',
				'fill-opacity' : 1,
				stroke : '#000',
				'stroke-width' : 1
			})
			circle.selectize({
				deepSelect : true
			});
			circle.resize();
			selected_tool = circle;
			selected_tool.data({"bordercolor":"#000","fill":"#ffffff","radius-x":100,"radius-y":100});
			break;
		case "ellipse":
			selected_tool = draw.ellipse(80, 50);
			selected_tool.center(event.clientX, event.clientY
					- canvas_offset_top)
			selected_tool.attr({
				fill : '#ffffff',
				'fill-opacity' : 1,
				stroke : '#000',
				'stroke-width' : 1
			})
			selected_tool.selectize({
				deepSelect : true
			});
			selected_tool.resize();
			selected_tool.data({"bordercolor":"#000","fill":"#ffffff","radius-x":80,"radius-y":50});
			break;
		case "polygon":
			polygon_arr = polygon_arr + event.clientX + ','
					+ (event.clientY - $("#canvas").offset().top) + " ";
			polygon_arr_temp = polygon_arr;
			// console.log(polyline_arr);
			if (selected_tool != undefined) {// 折线已在画布中，增加点线到折线
				selected_tool.plot(polygon_arr);
			} else {// 画一个新的折线polyline
				var polygon = draw.polygon(
						event.clientX + ',' + event.clientY
								- $("#canvas").offset().top).fill('none')
						.stroke({
							width : 1
						});
				selected_tool = polygon;

			}
			selected_tool.data({"bordercolor":"#fff","fill":"#000"});
			break;
		case "line":

			this.ox = event.clientX - $("#canvas").offset().left;
			this.oy = event.clientY - $("#canvas").offset().top;
			// console.log(this.ox+","+this.oy);

			var line = draw.line(this.ox, this.oy, this.ox, this.oy).stroke({
				width : 1
			})

			line.selectize({
				deepSelect : true
			});
			selected_tool = line;
			selected_tool.data({"width":"1","fill":"#000"});
			break;
		case "label":
			var text = draw.text("输入内容")
			text.font({
				//family : 'Helvetica',
				size : 20,
				anchor : 'middle',
				leading : '1em'
			})
			text.selectize({
				deepSelect : true
			});
			text.resize();
			text.attr('x', last_x);
			text.attr('y', last_y);
			text.style({
				fill : '#000'
			});
			selected_tool = text;
			selected_tool.data({"text":"双击输入内容","bordercolor":"#000","fill":"#000","size":25,"family":"Helvetica","leading":"1em"});
			break;
		case "curve": 
			/**参考http://justcoding.iteye.com/blog/2226354
			 * 二次贝塞尔曲线:M x0,y0 Q x1,y1 x2,y2
			 *    M 开始点 Q 控制点 1   通过M定义（x0,y0）为起点，用Q定义（x1,y1）为控制点，（x2,y2）为终点。
			 * 三次贝塞尔曲线指令：M x0,y0 C x1,y1 x2,y2 x3,y3  
			 *    M 开始点 C x1 y1, x2 y2, x y两个控制点(x1,y1)和(x2,y2)，(x,y)代表曲线的终点。
			 *    字母C表示特定动作与行为，这里需要大写，表示标准三次方贝塞尔曲线。*/
			var curvepath = "M" + last_x + " " + last_y + " Q" + (last_x )
					+ " " + (last_y );
			curvepath = curvepath + " ," + (last_x) + " " + (last_y);
			var curve = draw.path(curvepath);// 二次贝塞尔曲线
			
			curve.fill('transparent');
			curve.style('stroke', 'black');
			selected_tool = curve;
			selected_tool.data({"bordercolor":"#000","fill":"#000"});
			
			break;
		case "tofront":
			break;
		case "toback":
			break;
		case "4-vector":
			var group = draw.group()
			var v_line = draw.path('M 200 200 L 800 200').stroke({
				color : '#f06',
				opacity : 1,
				width : 1
			});
			var h_line = draw.path('M 500 10 L 500 400').stroke({
				color : '#f06',
				opacity : 1,
				width : 1
			});
			h_line.marker('end', 50, 50, function(add) {
				add.line(12.5, 12.5, 25, 25).stroke({
					width : 1
				});
				add.line(12.5, 37.5, 25, 25).stroke({
					width : 1
				});

				this.fill('#000000')
			})
			group.add(draw.text("高并发").move(200, 200));
			group.add(draw.text("低并发").move(800, 200))
			group.add(draw.text("低延迟").move(500, 10));
			group.add(draw.text("高延迟").move(500, 400));
			v_line.marker('end', 50, 50, function(add) {
				add.line(12.5, 12.5, 25, 25).stroke({
					width : 1
				});
				add.line(12.5, 37.5, 25, 25).stroke({
					width : 1
				});

				this.fill('#000000')
			})

			group.add(h_line);
			group.add(v_line);
			selected_tool = group;
			break;

		}
		SVG.on(selected_tool.node, 'dblclick.', dblclick);
		
		obj_set.add(selected_tool);
		cmdstack.undostack.push(selected_tool);
	} else {// 选择模式
		if(isResize){//resize状态
			return ;
		}
		if(isDragging){
			//console.log("mousedown,is dragging ,exit!");
			return ;
		}
		if(selection_model){//框选状态
			//console.log("mousedown,is selection_model ,exit!");
			selection_model=false;
			return ;
		}
	
		if(selection_zone==undefined&&selected_tool_id == 'select') 
	    {
	    		selection_zone=draw.rect(100, 100);
	    		selection_zone.attr({
		    		"fill-opacity" : 0
				});
	    		selection_zone.move(event.clientX,event.clientY-canvas_offset_top);
	    }
	    	
		is_mouse_down = true;
		//console.log("选择模式");
		var _isselected=false;//是否选中元素,true为选中
		var _current_item_postion=-1;//当前选择元素在面板中的空间层次,0为最低层，上层为依次加1
		var last_hit_ele;
		var _offset=10;//偏差
		var _x_hit=false;//x坐标击中
		var _y_hit=false;//y坐标击中
		if(selected_tool!=undefined) {
			if(document.getElementById(selected_tool.node.id)!=undefined){
				try{
				selected_tool.selectize(false);//清除前一次选中的元素
				}catch(exception){
					selected_tool=undefined;
				}
			}else{
				selected_tool=undefined;
			}
		}
		
		//selected_tool=undefined;
		//if(selected_tool!=undefined) selected_tool.selectize(false);//取消选 中
		obj_set.each(function(i) {
			//console.log("index:"+i+" ,mouse event(x,y)="+event.clientX+","+ event.clientY+" , bbox(x,y)= "+this.bbox().x+","+this.bbox().y+",(width,height)="+this.bbox().width+","+this.bbox().height);
			/**遍历所有当前面板中元素，查出点击事件位置下选中的元素（0-多个元素中，选择最上层的元素）
			 * position()返回元素的层次，从0开始
			 * */
			 _x_hit=event.clientX >= this.bbox().x+canvas_offset_left
				&& event.clientX <= this.bbox().x + this.bbox().width+canvas_offset_left;
			 _y_hit=event.clientY >= (this.bbox().y + canvas_offset_top-_offset)&& event.clientY <= this.bbox().y + this.bbox().height
				+ canvas_offset_top+_offset;
			
			//console.log(this.node.id+" ,x位置是否击中:"+_x_hit+","+event.clientX+">="+this.bbox().x +"&&"+event.clientX+"<="+this.bbox().x+"+"+this.bbox().width);
			//console.log(this.node.id+" ,y位置是否击中:"+_y_hit+","+event.clientY+">="+this.bbox().y+"+"+canvas_offset_top +"&&"+event.clientY+"<="+this.bbox().y+"+"+this.bbox().height+"+"+ canvas_offset_top);
			//if(this.inside(event.clientX-canvas_offset_left, event.clientY-canvas_offset_top)){
			if (_x_hit&&_y_hit) {
				_isselected=true;
				
				last_hit_ele=selected_tool ;
				selected_tool=this;//存储当前选中的元素
				////console.log(this.node.id+" hit it ,"+ this.type +" ,position=" +this.position());
				if(this.position()>_current_item_postion){//置换最顶层
					_current_item_postion=this.position();//保存当前位置
				}else{
					if(last_hit_ele!=undefined) {
						//console.log("record last hit ele");
						selected_tool=last_hit_ele;//选 中最上层的元素
					}
				}
				//跳出each循环
				// $('#ppmenu').css({left:event.clientX-this.bbox().width,top:this.bbox().y-20});
				// $('#ppmenu').show().delay(3000).hide(0);

			} else {
				//console.log("un hit");
				$("#canvas").css({
					"cursor" : "default"
				});
				this.selectize(false);
				//all_selected_ele_set.remove(this);
				hideedittool();
			}
			
			
		});
		if(_isselected){//被击中
			selection_model=false;
			hit_it=true;
			//console.log("选中操作"+selected_tool.node.id);
			selected_tool.selectize({
				deepSelect : false
			});
			selected_tool.draggable();
			selected_tool.ondrag(_event);// 拖动
			selected_tool.resize();
			//all_selected_ele_set.add(selected_tool);
			
			$("#canvas").css({
				"cursor" : "pointer"
			});
			//弹出工具面板
			showedittool(selected_tool.bbox().x, selected_tool.bbox().y+50, selected_tool.bbox().width,
					selected_tool.bbox().height)
		}

	}

}

var eleinzone=function(zone){
	obj_set.each(function(i) {
		if(zone.inside(this.bbox().x, this.bbox().y)
				||zone.inside(this.bbox().x+this.bbox().width, this.bbox().y)
				||zone.inside(this.bbox().x, this.bbox().y+this.bbox().height)
				||zone.inside(this.bbox().x+this.bbox().width, this.bbox().y+this.bbox().height)){
			
			this.selectize();
			this.draggable();
			this.ondrag(event);// 拖动
			this.resize();
		}
	});
}
// 鼠标移动
var mousemove = function(_event) {
	var event = _event.changedTouches && _event.changedTouches[0] || _event
	if (isDrawing && is_mouse_down) {
		if (selected_tool_id == 'rect') {
			selected_tool.width(Math.abs(event.clientX - last_x))
			selected_tool.height(Math.abs(event.clientY - last_y))

		} else if (selected_tool_id == 'line') {
			var _x = event.clientX - $("#canvas").offset().left;
			var _y = event.clientY - $("#canvas").offset().top;

			if (selected_tool != undefined) {
				// console.log(Math.abs(_y-this.oy)+","+Math.abs(_x-this.ox));
				if (shift_key_on && Math.abs(_y - this.oy) <= 10) {
					selected_tool.plot(this.ox, this.oy, _x, this.oy);
					// console.log("x line")
				} else if (shift_key_on && Math.abs(_x - this.ox) <= 10) {
					selected_tool.plot(this.ox, this.oy, this.ox, _y);
					// console.log("y line")
				} else {
					// console.log("line")
					selected_tool.plot(this.ox, this.oy, _x, _y);
				}
			}
		} else if (selected_tool_id == 'circle') {
			// console.log(event.clientY+","+last_y);
			// selected_tool.radius((event.clientY-last_y)/2);
			selected_tool.radius((event.clientY - last_y) / 2,
					(event.clientY - last_y) / 2);
		} else if (selected_tool_id == 'ellipse') {
			// console.log(event.clientY+","+last_y);
			// selected_tool.radius((event.clientY-last_y)/2);
			selected_tool.radius((event.clientX - last_x) / 2,
					(event.clientY - last_y) / 2);
		} else if (selected_tool_id == 'label') {

		} else if (selected_tool_id == 'polygon') {
			if (selected_tool != undefined) {
				polygon_arr_temp = polygon_arr + event.clientX + ','
						+ (event.clientY - $("#canvas").offset().top) + " ";
				selected_tool.plot(polygon_arr_temp);
			}
		} else if (selected_tool_id == 'image') {
			// selected_tool.move(event.clientX,event.clientY-$("#canvas").offset().top)
		}else if(selected_tool_id == 'curve'){
			var curvepath = "M" + last_x + " " + last_y + " Q" + (last_x + 100)
			+ " " + (last_y + 200);
		curvepath = curvepath + " ," + (event.clientX) + " " + (event.clientY);
		
		var curve = selected_tool.plot(curvepath);
		curve.fill('transparent');
		curve.style('stroke', 'black');
		selected_tool = curve;
		selected_tool.data({"type":"curve","bordercolor":"#000","fill":"#000"});
		}
			
	}else{
		if(is_mouse_down&&selected_tool_id == 'select'&&!isDragging&&!hit_it){//选择模式
			//console.log("mousemove,标识为框选模式");
			hit_it=false;
			selection_model=true;
			//console.log(last_x+","+last_y +" >>"+event.clientX+","+event.clientY);
		    if(selection_zone==undefined) {
		    	selection_zone=draw.rect(100, 100);
		    	selection_zone.attr({
		    		"fill-opacity" : 0
				});
		    	selection_zone.move(event.clientX,event.clientY);
		    	
		    }
		    selection_zone.width(Math.abs(event.clientX - selection_zone.bbox().x))
			selection_zone.height(Math.abs(event.clientY - selection_zone.bbox().y))
			selection_zone.attr({
				fill : '#ffffff',
				"stroke" : '#000',
				"stroke-width" : '1',
				"stroke-dasharray":"5,5"
			});
		}
		
	}
}
var selection_zone ;//选择框
// 鼠标松开
var mouseup = function(_event) {
	
	var event = _event.changedTouches && _event.changedTouches[0] || _event
	shift_key_on = false;
	if (isDrawing && is_mouse_down) {
		is_mouse_down = false;
		isDrawing = false;
		
		if (selected_tool_id == 'line') {
			/*
			 * selected_tool.plot(this.ox, this.oy, event.clientX,
			 * event.clientY-$("#canvas").offset().top);
			 */
			if(selected_tool.width()<10){
				selected_tool.plot(this.ox, this.oy, this.ox+100, this.oy+100);
			}
		}else if (selected_tool_id == 'circle') {
			if(selected_tool.attr("rx")<10){
				selected_tool.radius(50,50)
			}
		}else if (selected_tool_id == 'ellipse') {
			if(selected_tool.attr("rx")<15&&selected_tool.attr("ry")<15){
				
				selected_tool.radius(80,50)
			}
		}
		else if (selected_tool_id == 'polygon') {
			
			is_mouse_down = true;
			isDrawing = true;// 需要在界面上多次点击
			// console.log(selected_tool.array());
			return;
		} else if (selected_tool_id == 'image') {
			// selected_tool.move(event.clientX,event.clientY-$("#canvas").offset().top)

		}
		selected_tool.resize();
		// selected_tool.draggable();
		selected_tool.selectize();
		$("#canvas").css({
			"cursor" : "default"
		});
	}
	if (!isDrawing && is_mouse_down&&!isDragging) {
		is_mouse_down=false;
		if(selection_zone!=undefined){
			//console.log("mouse up>>NO1.框选选区内元素");
			eleinzone(selection_zone);
			selection_zone.remove();
			selection_zone=undefined;
			selection_model=false;//结束本次框选模式
			//console.log("mouse up>>NO2.结束本次框选模式");
			hit_it=false;
		}
		return;
	}
}
// 双击
var dblclick = function(_event) {
	var event = _event.changedTouches && _event.changedTouches[0] || _event
	isDrawing = false;// 需要在界面上多次点击
	is_mouse_down = false;
	polyline_arr = "";
	$("#canvas").css({
		"cursor" : "default"
	});
	//console.log(selected_tool.type);
	showtexteditor(event.clientX, event.clientY, selected_tool.bbox().width,
			selected_tool.bbox().height);
	$("#colorInput").show();
	$("#colorInputlabel").show();
	//console.log(selected_tool.type);
	switch (selected_tool.type) {
	case "text": //文字
		$("#wordattr").show();
		$("#colorattr").show();
		$("#arrowattr").hide();
		$("#radisattr").hide();
		$("#circelattr").hide();
		$("#fontattr").show();
		$("#dashattr").hide();
		$("#colorInput").val(selected_tool.data("fill"));
		$("#txtInput").val(selected_tool.data("text"));
		$("#fontsize").val(selected_tool.data("size"));
		$("#bordercolorInput").val(selected_tool.data("bordercolor"));
		// $("#bordercolorInput").hide();
		break;
	case "line"://直线
		$("#dashattr").show();
		$("#arrowattr").show();
		$("#colorattr").show();
		$("#radisattr").hide();
		$("#wordattr").hide();
		$("#circelattr").hide();
		$("#fontattr").hide();
		$("#bordercolorInput").val(selected_tool.data("bordercolor"));
		$("#colorInput").val(selected_tool.data("fill"));
		break;
	case "path"://
		$("#dashattr").show();
		$("#arrowattr").show();
		$("#colorattr").show();
		$("#wordattr").hide();
		$("#fontattr").hide();
		$("#circelattr").hide();
		$("#colorInput").hide();
		$("#colorInputlabel").hide();
		$("#bordercolorInput").val(selected_tool.data("bordercolor"));
		$("#colorInput").val(selected_tool.data("fill"));
		break;
	case "ellipse"://椭圆
	case "circle"://圆
		$("#dashattr").show();
		$("#fontattr").hide();
		$("#circelattr").show();
		$("#wordattr").hide();
		$("#colorattr").show();
		$("#arrowattr").hide();
		$("#bordercolorInput").val(selected_tool.data("bordercolor"));
		$("#colorInput").val(selected_tool.data("fill"));
		$("#circle-radius-x").val(selected_tool.attr("rx"));
		$("#circle-radius-y").val(selected_tool.attr("ry"));
		break;
	case "rect"://矩形
		$("#dashattr").show();
		$("#circelattr").show();
		$("#wordattr").hide();
		$("#colorattr").show();
		$("#arrowattr").hide();
		$("#fontattr").hide();
		//$("#circle-radius-x").val(50);
		//$("#circle-radius-y").val(50);
		$("#bordercolorInput").val(selected_tool.data("bordercolor"));
		$("#colorInput").val(selected_tool.data("fill"));
		$("#circle-radius-x").val(selected_tool.data("radius-x"));
		$("#circle-radius-y").val(selected_tool.data("radius-y"));
		break;
	case "polygon"://多边形
		$("#dashattr").show();
		$("#wordattr").hide();
		$("#colorattr").show();
		$("#arrowattr").hide();
		$("#circelattr").hide();
		$("#fontattr").hide();
		$("#bordercolorInput").val(selected_tool.data("bordercolor"));
		$("#colorInput").val(selected_tool.data("fill"));
		break;
	}
}
var showedittool= function(x, y, width, height){
	var div = $("#editToolPanel");
	div.css("left", x - canvas_offset_left +width + "px");
	div.css("top", (y) + "px");
	$("#editToolPanel").show();
}
var hideedittool=function(){
	$("#editToolPanel").hide();
}
// 文本编辑
var showtexteditor = function(x, y, width, height) {
	var div = $("#editorPanel");
	div.css("left", x - canvas_offset_left - (div.width() / 2) + "px");
	div.css("top", (y) + "px");
	$("#editorPanel").show();
};
var clipboard;
function oncopy(){
	clipboard=selected_tool.clone();
}
function onpaste(){
	  if(clipboard!=undefined) {
		  clipboard.dmove(40, 50)
	  }
	  
	  
	  var group = draw.group()
	  group.add(clipboard);
	  obj_set.add(clipboard);
	  selected_tool.selectize(false);
	  clipboard.selectize({
			deepSelect : true
	  });
	  clipboard.resize();
	  cmdstack.undostack.push(clipboard);
	  clipboard=undefined;
	  selected_tool=clipboard;//切换当前选择对象
}
//键盘事件
var keydown=function(event){
	//console.log(event.which);
  if(event.which == 46)   //delete键盘
  {
	tool_select(document.getElementById("delBbn"));
  }else if(event.which == 16){//Shift键
		//画直线
		shift_key_on=true;
  }
  //37 - 40按键 左、上、右、下(方向键) Enter键13 Ctrl键17
}